package cn.iocoder.yudao.module.resource;

import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.module.infra.tts.impl.bytedance.ByteDanceTtsRequest;
import cn.iocoder.yudao.module.infra.tts.impl.bytedance.ByteDanceTtsResponse;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;

public class ByteDanceVoiceCloneClient {
    private static final String HOST = "https://openspeech.bytedance.com";
    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) {
        String appid = "9383853511";
        String token = "ZialHVjYdNhrIZ5RQfIN5dGNlMEJjXYl";
        String spkId = "S_73jvNpbn1";
        String audioPath = "E:\\dudu\\docs\\00声纹原音-第2版-10s-20s\\17-巧风-底板-少妇-甜度4-媚度6-尖度4.MP3";

        try {
            train(appid, token, audioPath, spkId);
            getStatus(appid, token, spkId);
            //byte[] bytes = voiceClone(appid, token, spkId, "你好，我是小爱同学。");
            //FileUtil.writeBytes(bytes, "E:\\ai\\output\\1.mp3");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void train(String appid, String token, String audioPath, String spkId) throws IOException {
        String url = HOST + "/api/v1/mega_tts/audio/upload";

        // Base64 编码音频文件
        String[] encodedData = encodeAudioFile(audioPath);
        String audioBase64 = encodedData[0];
        String audioFormat = encodedData[1];

        // 构建请求 JSON
        JSONObject audioObj = new JSONObject();
        audioObj.put("audio_bytes", audioBase64);
        audioObj.put("audio_format", audioFormat);

        JSONArray audios = new JSONArray();
        audios.put(audioObj);

        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("appid", appid);
        requestBodyJson.put("speaker_id", spkId);
        requestBodyJson.put("audios", audios);
        requestBodyJson.put("source", 2);
        requestBodyJson.put("language", 0);
        requestBodyJson.put("model_type", 1);

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(
                        requestBodyJson.toString(),
                        MediaType.parse("application/json")))
                .addHeader("Authorization", "Bearer;" + token)
                .addHeader("Resource-Id", "volc.megatts.voiceclone")
                .build();

        // 发送请求
        try (Response response = client.newCall(request).execute()) {
            System.out.println("Status code: " + response.code());

            if (!response.isSuccessful()) {
                throw new IOException("请求错误: " + response.body().string());
            }

            System.out.println("Headers: " + response.headers());
            System.out.println("Response body: " + response.body().string());
        }
    }

    public static void getStatus(String appid, String token, String spkId) throws IOException {
        String url = HOST + "/api/v1/mega_tts/status";

        // 构建请求 JSON
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("appid", appid);
        requestBodyJson.put("speaker_id", spkId);

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(
                        requestBodyJson.toString(),
                        MediaType.parse("application/json")))
                .addHeader("Authorization", "Bearer;" + token)
                .addHeader("Resource-Id", "volc.megatts.voiceclone")
                .build();

        // 发送请求
        try (Response response = client.newCall(request).execute()) {
            System.out.println("状态查询结果: " + response.body().string());
        }
    }

    public static byte[] voiceClone(String appid, String token, String spkId, String text) throws IOException {
        ByteDanceTtsRequest ttsRequest = new ByteDanceTtsRequest(appid);
        ttsRequest.setText(text);
        ttsRequest.setSpkId(spkId);
        String url = HOST + "/api/v1/tts";
        RequestBody body = RequestBody.create(JSON.toJSONString(ttsRequest), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Authorization", "Bearer; " + token)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String bodyStr = response.body().string();
            ByteDanceTtsResponse ttsResponse = JSON.parseObject(bodyStr, ByteDanceTtsResponse.class);
            return ttsResponse.getDecodedData();
        }
    }

    private static String[] encodeAudioFile(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileContent = Files.readAllBytes(file.toPath());
        String encoded = Base64.getEncoder().encodeToString(fileContent);

        String fileName = file.getName();
        int dotIndex = fileName.lastIndexOf('.');
        String format = dotIndex > 0 ? fileName.substring(dotIndex + 1) : "";

        return new String[]{encoded, format};
    }
}
